<?php
/**
 * TomatoCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: build.phtml 4703 2010-08-16 17:05:16Z huuphuoc $
 * @since 		2.0.2
 */
?>
<?php
$this->headTitle($this->translate('menu_build_title'));
$this->headLink()->appendStylesheet($this->APP_STATIC_SERVER . '/skins/admin/default/css/form.css')
        ->appendStylesheet($this->APP_STATIC_SERVER . '/skins/admin/default/css/menu.css');
//$this->headLink()
//	->appendStylesheet($this->APP_STATIC_SERVER . '/js/jquery.ui/themes/base/ui.all.css')
//	->appendStylesheet($this->APP_STATIC_SERVER . '/js/jquery.ui/themes/base/ui.core.css')
//	->appendStylesheet($this->APP_STATIC_SERVER . '/js/jquery.ui/themes/base/ui.resizable.css')
//	->appendStylesheet($this->APP_STATIC_SERVER . '/js/jquery.ui/themes/base/ui.dialog.css');
$this->headScript()
	->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.ui/jquery.ui.core.min.js')
        ->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.ui/jquery.ui.widget.min.js')
        ->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.ui/jquery.ui.mouse.min.js')
	->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.ui/jquery.ui.sortable.min.js')
        ->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.ui/jquery.effects.core.min.js')
        ->appendFile($this->APP_STATIC_SERVER . '/skins/admin/default/js/menu.js')
        ->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.json-2.3.min.js')
        ->appendFile($this->APP_STATIC_SERVER . '/public/js/jquery.validate.js');
//	->appendFile($this->APP_STATIC_SERVER . '/js/jquery.ui/ui.draggable.js')
//	->appendFile($this->APP_STATIC_SERVER . '/js/jquery.ui/ui.droppable.js')
//	->appendFile($this->APP_STATIC_SERVER . '/js/jquery.ui/ui.dialog.js')
//	->appendFile($this->APP_STATIC_SERVER . '/js/jquery.editinplace/jquery.editinplace.packed.js')


/**
 * @since 2.0.7
 */
//->appendFile($this->APP_STATIC_SERVER . '/js/tomato/treetable.js');
?>
<div id="r-heading">
    <img src="<?php echo $this->APP_STATIC_SERVER . '/skins/admin/default/images/menu-48x48.png'; ?>" alt=""/>
    <span><?php echo $this->translate('menu_build_breadcrumb'); ?></span>
</div>
<?php
$message = $this->flashMessenger();
if ($message) {
?>
    <div id="message"><?php echo $message; ?></div>
<?php } ?>
<div style ="width: 30%; float: left">
    <form name="frmAddMenu" id="frmAddMenu" action="" method="post">
        <div class="row">
            <label for="name"><?php echo $this->translate('menu_name'); ?></label>
            <input type="text" name="name" id="name"/>
        </div>
        <div class="row">
            <label for="description"><?php echo $this->translate('menu_description'); ?>:</label>
            <textarea cols="25" rows="5" id="description" name="description"></textarea>
        </div>
        <div class="row">
            <label><?php echo $this->translate('menu_language'); ?></label>
            <?php
            echo $this->languageSelector(array(
                'id' => 'languageSelector',
                'name' => 'language',
                    ), $this->translatableData);
            ?>
        </div>
        <div class="row">
            <label><?php echo $this->translate('menu_source_item'); ?>:</label>
            <div class="translatable translationSourceItems">
                <?php
                echo $this->translatableMenu(array(
                    'id' => 'sourceItem',
                    'name' => 'sourceItem',
                    'selected' => (null == $this->sourceMenu) ? null : $this->sourceMenu->id,
                    'disabled' => (null == $this->sourceMenu) ? null : $this->sourceMenu->id,
                        ), $this->lang);
                ?>
            </div>
        </div>
        <div class="row">
            <input type="hidden" name="items" value="" id="items"/>
            <input type="submit" name="submit" id="submit" value="<?php echo $this->translate('common_submit', 'core'); ?>" class="button" />
            <input type="reset" name="reset" id="reset" value="<?php echo $this->translate('common_reset', 'core'); ?>" class="button" />
        </div>
    </form>
</div>
<div style ="width: 40%; float: left;">
    <div class="box" id="menu-items">
        <div class="b-title"><?php echo $this->translate('menu_item_head')?></div>
        <div class="b-container">
            <p id="menu-guide"><?php echo $this->translate('menu_items_guide')?></p>
            <ul id="menu" class="menu">
                
            </ul>
        </div>
    </div>

</div>
<div style ="width: 25%; float: left;">
    <div class="box" id="custom-link">
        <div class="b-title"><?php echo $this->translate('menu_custom_link_box_title')?></div>
        <div class="b-container">
            <form id="frmAddCustomLink" method="post" action="">
                <div class="row">
                    <label for="custom-link-label"><?php echo $this->translate('menu_custom_link_label')?></label>
                    <input type="text" name="custom-link-label" id="custom-link-label" size="30"/>
                </div>
                <div class="row">
                    <label for="custom-link-link"><?php echo $this->translate('menu_custom_link_link')?></label>
                    <input type="text" name="custom-link-link" id="custom-link-link" size="30"/>
                </div>
                <div class="row">
                    <input type="button" value="<?php echo $this->translate('menu_item_add')?>" id="add-custom-link" class="button"/>
                </div>
            </form>
        </div>
    </div>
<?php
$count = count($this->categorySet);
if ($count == 0) {
?>
    <div style="color: #fc0202;">
    <?php echo $this->translate('category_list_not_found', 'category'); ?>
    </div>
<?php
} else {
    foreach ($this->categorySet as $module => $categories) {
?>
    <div class="box category-list">
        <div class="b-title"><?php echo sprintf($this->translate('menu_categories_box_title'), $module); ?></div>
        <div class="b-container">
            <ul id="<?php echo $module?>-categories">
        <?php
                $rightStack = array();
                foreach ($categories as $category) {
                    while (count($rightStack) > 0 && $rightStack[count($rightStack) - 1] < $category->rht) {
                        array_pop($rightStack);
                    }
        ?>
                    <li id="category-<?php echo $category->id ?>">
                        <span>
                            <input type="checkbox" class="chkId" value="<?php echo $category->id; ?>"/>
                        </span>
                        <span><?php echo str_repeat('--', count($rightStack)) . $category->name; ?></span>
                    </li>
        <?php
                    $rightStack[] = $category->rht;
                }
        ?>
            </ul>
            <div class="row">
                <input type="button" value="<?php echo $this->translate('menu_item_add')?>" id="add-<?php echo $module?>-category-link" class="button add-category-link" />
                <span class="add-tree">
                    <input type="checkbox" value="" name="chk_add_tree" class="chk-add-tree"/><label for="chk_add_tree"><?php echo $this->translate('menu_item_add_category_tree')?></label>
                </span>
            </div>
        </div>
    </div>
<?php
    }
}
?>
<?php
    if(count($this->pages) > 0){
?>
    <div class="box page-list">
        <div class="b-title"><?php echo sprintf($this->translate('menu_pages_box_title'), $module); ?></div>
        <div class="b-container">
            <ul id="pages">
        <?php
                $rightStack = array();
                foreach ($this->pages as $page) {
                    while (count($rightStack) > 0 && $rightStack[count($rightStack) - 1] < $page->rht) {
                        array_pop($rightStack);
                    }
        ?>
                    <li id="page-<?php echo $page->id ?>">
                        <span>
                            <input type="checkbox" class="chkId" value="<?php echo $page->id; ?>"/>
                        </span>
                        <span><?php echo str_repeat('--', count($rightStack)) . $page->name; ?></span>
                    </li>
        <?php
                    $rightStack[] = $page->rht;
                }
        ?>
            </ul>
            <div class="row">
                <input type="button" value="<?php echo $this->translate('menu_item_add')?>" id="add-page-link" class="button add-page-link" />
                <span class="add-tree">
                    <input type="checkbox" value="" name="chk_add_tree" class="chk-add-tree"/><label for="chk_add_tree"><?php echo $this->translate('menu_item_add_page_tree')?></label>
                </span>
            </div>
        </div>
    </div>
<?php
    }
?>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        /**
         * Add custom link
         */
        $("#add-custom-link").click(function(){
            var customLinkLabel = $("#custom-link-label").val();
            var customLinkLink = $("#custom-link-link").val();
            if(customLinkLabel =='' || customLinkLink == ''){
                var ul = "<ul class='warning'>";
                if(customLinkLabel == ''){
                    ul+="<li class='error'><?php echo $this->translate('menu_item_custom_link_label_required')?></li>";
                }
                if(customLinkLink == ''){
                    ul+="<li class='error'><?php echo $this->translate('menu_item_custom_link_link_required')?></li>";
                }
                $("#custom-link .b-container ul").remove();
                $("#custom-link .b-container").prepend(ul);
                return false;
            }
            $.ajax({
                    url: '<?php echo $this->url(array(), 'menu_menu_route') ?>',
                    data: {label: customLinkLabel, link: customLinkLink, type: 'custom'},
                    type: 'POST',
                    success: function(response){
                        var result = $.evalJSON(response);
                        if(result.status == 'ok'){
                            var ordering = $('.menu-item').length  + 1;
                            addItem('custom',result.item.id, result.item.label, result.item.link, 0, result.item.parent_id, ordering);
                            $("#custom-link-label").val('');
                            $("#custom-link-link").val('');
                        }
                    }

                });
           
        });

        $(".add-category-link").click(function(){
            var id = $(this).attr('id');
            var params = id.split('-');
            var ul = $("#"+params[1] + "-categories");
            var chk = ul.find("input:checked");
            if(chk.length == 0){
                ul.parent().find(".warning").remove();
                ul.parent().prepend(
                    '<ul class="warning"><li style="color: #f20000;">Please select category to import</li></ul>'
                );
                return false;
            }
            getItem(chk, 0, 'category');
            chk.removeAttr('checked');
        });
        $(".add-page-link").click(function(){
//            var id = $(this).attr('id');
//            var params = id.split('-');
            var ul = $("#pages");
            var chk = ul.find("input:checked");
            if(chk.length == 0){
                ul.parent().find(".warning").remove();
                ul.parent().prepend(
                    '<ul class="warning"><li style="color: #f20000;">Please select category to import</li></ul>'
                );
                return false;
            }
            getItem(chk, 0, 'page');
            chk.removeAttr('checked');
        });
        
        $('#menu').bind('click', function(e) {
            if ( e.target && e.target.className ) {
                var a = $(e.target);
                var mi =  $('#' + a.attr('rel'));
                var data = mi.getItemData();
                if ( a.hasClass('mi-activate')) {
                    if(!mi.hasClass("mi-actived")){
                        mi.find(".mi-setting").slideDown(300);
                        mi.addClass("mi-actived");
                        a.removeClass('expand').addClass('collapse');

                        if( ! mi.data('data') ) {
                              mi.data( 'data', mi.getItemData() );
                        }
                    }else{
                        mi.find(".mi-setting").slideUp(300);
                        mi.removeClass("mi-actived");
                        a.removeClass('collapse').addClass('expand');
                        if( mi.data('data') ) {
                              mi.removeData( 'data');
                        }
                    }
                    return false;
                } else if ( a.hasClass('mi-save') ) {
                    mi.find('.mi-title').html(mi.find('.mi-label').val());
                    mi.find('.mi-setting').animate({backgroundColor : '#5d1'}, 50).animate({backgroundColor: '#fff'}, 50);
                    mi.data('data', mi.getItemData());
                    return false;//that.eventOnClickMenuSave(e.target);
                } else if ( a.hasClass('mi-delete') ) {
                    $.ajax({
                        url: '<?php echo $this->url(array(), 'menu_item_delete') ?>',
                        data: {id: data.id},
                        type: 'POST',
                        success: function(response){
                            var result  = $.evalJSON(response);
                            if(result.status){
                                mi.fadeOut('slow');
                            }else{
                                alert('');
                            }
                        }
                    })
                    return false;//that.eventOnClickMenuDelete(e.target);
                } else if ( a.hasClass('mi-cancel') ) {
                    mi.setItemData(mi.data('data'));
                    mi.find('.mi-setting').animate({backgroundColor : 'yellow'}, 50).animate({backgroundColor: '#fff'}, 50);
                    return false;
                }
            }
        });
        
        /**
	 * Validate form
	 */
	$('#frmAddMenu').validate({
		rules: {
			name: {
				required: true
			}
		},
		messages: {
			name: {
				required: '<?php echo $this->translate('menu_name_required'); ?>'
			}
		}
	});
        /**
        * When submit form
        */
        $('#frmAddMenu').submit(function(){
            var items = new Array();
            $('.menu-item').each(function(){
                var item = {
                  id: $(this).find('.mi-id').val(),
                  label : $(this).find('.mi-label').val(),
                  link : $(this).find('.mi-link').val(),
                  parent_id : $(this).find('.mi-parent-id').val(),
                  depth : $(this).find('.mi-depth').val(),
                  ordering : $(this).find('.mi-ordering').val(),
                  target : ($(this).find('.mi-target').attr('checked')) ? $(this).find('.mi-target').val() : 0,
                  type : $(this).find('.mi-type').val()
                };
                items.push(item);
                
            });
            $('#items').val($.toJSON(items));
        });
    });
    
    function hideGuide(){
        if($("#menu-guide").css('display') != 'none') $("#menu-guide").hide();
    }
    /**
     * 
     */
    function getItem(chk, i, type){
        if(i < chk.length){
            
            $.ajax({
                    url: '<?php echo $this->url(array(), 'menu_menu_route') ?>',
                    data: {id: chk.eq(i).val(), type: type},
                    type: 'POST',
                    success: function(response){
                        var result = $.evalJSON(response);
                        if(result.status == 'ok'){
                            var ordering = $('.menu-item').length  + 1;
                            addItem(type,result.item.id, result.item.label, result.item.link, 0, result.item.parent_id, ordering);
                            getItem(chk, i+ 1);
                        }
                    }

                });
        }else{
            return false;
        }
    }   
    function addItem(type, id, label, link, depth, parent_id, ordering ){
        
        $("#menu").append(
            '<li id="menu-item-' + id + '" class="menu-item mi-type-'+ type + ' mi-depth-' + depth +'">'+
            '		<div class="mi-top">'+
            '			<span class="mi-title">' + label + '</span>' +
            '			<span class="mi-controls">' +
            '                   <span>'+ type.substring(0,1).toUpperCase() + type.substring(1) +' Link'+ '</span>' +
            '				<a class="mi-activate expand" href="" rel="menu-item-' + id + '"></a>' +
            '			</span>' +
            '		</div>' +
            '		<div class ="mi-setting" style="display: none;">' +
            '                 <p>'+
            '                       <label for="">Label</label>'+
            '                       <input type="text" size="25" value="' + label +'" name="" class="mi-label">'+
            '			</p>'+
            '			<p>' +
            '				<label for="">Link</label>' +
            '                       <input type="text" size="40" value="' + link + '" name="" class="mi-link">' +
            '			</p>'+
            '                 <p>'+
            '                       <input class="mi-target f-left" type="checkbox" name="" value="1"/>'+
            '                       <label for="">Open in new window</label>'+
            '                 </p>'+
            '			<div class="mi-actions">' +
            '				<a href="" class="mi-save" rel="menu-item-' + id + '">Save</a> | <a href="" class="mi-delete" rel="menu-item-' + id + '">Remove</a> | <a href="" class="mi-cancel" rel="menu-item-' + id + '">Cancel</a>' +
            '			</div>'+
            '		</div>' +
            '		<ul class="menu-item-transport"></ul>' +
            '           <span>'+
            '               <input type="hidden" class="mi-id" value="' + id + '"/>'+
            '               <input type="hidden" class="mi-parent-id" value="' + parent_id + '"/>'+
            '               <input type="hidden" class="mi-ordering" value="' + ordering +'"/>'+
            '               <input type="hidden" class="mi-depth" value="'+ depth +'"/>' +
            '               <input type="hidden" name="" class="mi-type" value="' + type + '"/>'+
            '           </span>' +
            '</li>'
        );

    }
    /**
     * Get max right of menu items
     */
    function getMaxRight(items){
        var max = 0;
        for(var i = 0; i< items.length; i++){
            if(items[i].rht > max) max = items[i].rht;
        }
        return max;
    }
</script>
